package com.se.clickableText;

import com.se.utils.ClientUtils;
import javafx.scene.input.MouseButton;
import javafx.scene.text.Text;

import java.util.ArrayList;
import java.util.List;

public class ClickableText extends Text {
    private final Runnable onClickAction;
    private static final String originStyle = "-fx-fill: #0078d4; -fx-cursor: hand;";

    public ClickableText(String text, Runnable onClick) {
        super(text);
        this.onClickAction = onClick;
        setStyle(originStyle);
        initMouseHandlers();
    }

    public static Text createAtText(String text, boolean self) {
        Text atText = new Text(text);
        if(self) {
            atText.getStyleClass().addAll("mention", "mention-self");
        }
        else {
            atText.getStyleClass().addAll("mention","mention-other");
        }

        return atText;
    }

    private void initMouseHandlers() {
        setOnMouseClicked(e -> {
            if(e.getButton() == MouseButton.PRIMARY) {
                onClickAction.run();
                e.consume();
            }
        });

        setOnMouseEntered(e -> setStyle(originStyle + "-fx-underline: true;"));

        setOnDragExited(e -> setStyle(originStyle));
    }

    public static List<Text> createRichMessage(String rawText) {
        List<Text> texts = new ArrayList<>();
        String[] parts = rawText.split("//split//");

        for(int i = 0; i< parts.length; i++) {
            texts.add(new Text(parts[i]));
            if(i < parts.length - 1) {
                ClickableText click = new ClickableText("点击",
                        () -> ClientUtils.information_Alert("Clicked!"));
                texts.add(click);
            }
        }
        return texts;
    }
}
